package com.tanhua.app.service;


import com.tanhua.app.interceptor.UserHolder;
import com.tanhua.commons.utils.Constants;
import com.tanhua.config.template.AipTemplate;
import com.tanhua.config.template.HuanXinTemplate;
import com.tanhua.config.template.OssTemplate;
import com.tanhua.config.template.SmsTemplate;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.pojo.User;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.model.pojo.UserInfo;
import com.tanhua.model.vo.HuanXinUserVo;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private AipTemplate aipTemplate;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @DubboReference
    private UserApi userApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private UserFreezeService userFreezeService;

    @Autowired
    private MqMessageService mqMessageService;

    private String CHECKCODE="CHECK_CODE_";

    public void sendCode(String phone) {
        //判断用户是否冻结
        User user = userApi.findByMobiles(phone);
        if (user != null){
            userFreezeService.freezeCheck(user.getId(),"1");
        }
        //1.生成验证码
        //String codes = RandomStringUtils.randomNumeric(5);
        //2.发送短信
        //smsTemplate.sendSms(phone,codes);
        String codes ="123456";
        //3.将验证码保存到Redis中
        redisTemplate.opsForValue().set(CHECKCODE+phone,codes, Duration.ofMinutes(5));
    }

    //用户登录校验
    public Map loginVerification(String phone, String codes) {
        //1.从redis中获取验证码
        String redisCodes = redisTemplate.opsForValue().get(CHECKCODE + phone);
        //2.校验验证码
        if (!codes.equals(redisCodes) || StringUtils.isBlank(redisCodes)){
            throw new RuntimeException("验证码错误");
        }
        //3.判断用户是否注册
        User user = userApi.findByMobiles(phone);
        boolean isNew = false;
        String type = "0101";
        if (user == null) {
            type = "0102";
            user = new User();
            user.setMobile(phone);
            user.setPassword(DigestUtils.md5Hex("123456"));
            //新增用户并返回主键
            Long id = userApi.save(user);
            user.setId(id);
            isNew = true;

            //将新注册用户信息注册到环信
            String hxUserName = Constants.HX_USER_PREFIX+user.getId();
            Boolean hxBoolean = huanXinTemplate.createUser(hxUserName, Constants.INIT_PASSWORD);
            //如果环信注册成功将环信的账号和密码设置到user信息中
            if (hxBoolean){
                user.setHxUser(hxUserName);
                user.setHxPassword(Constants.INIT_PASSWORD);
                userApi.update(user);
            }
        }
        //4.登录成功,生成token
        Map params = new HashMap();
        params.put("id",user.getId());
        params.put("mobile",phone);

        String token = JwtUtils.getToken(params);
        //5.封装数据并返回结果
        Map retMap = new HashMap();
        retMap.put("token",token);
        retMap.put("isNew",isNew);

        //登录发送消息
        mqMessageService.sendLogMessage(user.getId(),type,"user","");
        return retMap;
    }

    //用户首次登录完善资料
    public void loginReginfo(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }


    public void updateHead(MultipartFile headPhoto, Long id) throws IOException {
        //1.将照片上传到阿里云oss
        String imageUrl = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        //2.调用百度云判断是否包含人脸
        boolean detect = aipTemplate.detect(imageUrl);
        //3.不包含人脸抛出异常
        if (!detect){
            throw new RuntimeException("不包含人脸");
        }else {
            //4.包含人脸调用api更新
            UserInfo userInfo = new UserInfo();
            userInfo.setId(id);
            userInfo.setAvatar(imageUrl);
            userInfoApi.update(userInfo);
        }
    }
}
